import { get, put } from '@/util/http'
import { Shape } from '@antv/x6'
import { v4 as uuid } from 'uuid'

const approvalConfig = {}

const getOrg = async () =>
  await get('/queryGlobalValueByKey', {
    fieldNameKey: approvalConfig.orgEnvIdentifier,
  })

const getApp = async () =>
  await get('/queryGlobalValueByKey', {
    fieldNameKey: approvalConfig.appOnlyIdentifier,
  })

const getUser = async () =>
  await get('/queryGlobalValueByKey', {
    fieldNameKey: approvalConfig.userEnvIdentifier,
  })


const leftNode = [
  {
    uuid: 'u_f4b6111d547449eba725d6e3a3d581ee_u',
    id: 1,
    identifier: 'UserTask',
    name: 'UserTask',
    cnName: '审批',
    description: '',
    parentUuid: 'u_cb4d63ee696e4d2488243dd69ce8e0e5_u',
    status: 1,
    color: null,
    icon: '&#xe7d5;',
    iconDark: '&#xe7d5;',
    leadImage: '@/assets/img/examine.png',
    images: null,
  },
  {
    uuid: 'u_62b4c8eed5cc43dea2c1e44cfc2a81b1_u',
    id: 2,
    identifier: 'CopyTo',
    name: 'CopyTo',
    cnName: '抄送',
    description: '',
    parentUuid: 'u_cb4d63ee696e4d2488243dd69ce8e0e5_u',
    status: 1,
    color: null,
    icon: '&#xe7d5;',
    iconDark: '&#xe7d5;',
    leadImage: '@/assets/img/copy.png',
    images: null,
  },
  
]

const nodeInfoList = {
  StartEvent: {
    type: 'StartEvent',
    cnName: '开始',
    dataType: '',
    identifier: 'StartEvent',
    description: '',
    dataKey: '',
    StartEvent: null,
  },
  EndEvent: {
    type: 'EndEvent',
    cnName: '结束',
    dataType: '',
    dataKey: 'EndEvent',
    identifier: 'EndEvent',
    description: '',
    EndEvent: null,
  },
  
  UserTask: {
    type: 'UserTask',
    cnName: '审批',
    dataType: '',
    identifier: `i_${uuid().replace(/-/g, '')}_i`,
    description: '',
    dataKey: '',
    UserTask: {
      approvalUserNeed: 1,
      approvalUserSetType: 1,
      approvalSubmitUserType: 1,
      approvalType: 1,
      noUserSkipType: 1,
      approvalUserValue: [],
      approvalUser: [
        // {
        //   assigneeType: '',
        //   toGroupType: '',
        //   value: '',
        // },
      ],
      countersignRules: [
        // {
        //   approvalResultType: '会签审批结果：1-同意 2-拒绝',
        //   judgeRule: '判断方式：1-比列 2-一票否决',
        //   approvalRate: '百分比',
        // },
      ],
      defaultApprovalResult: '',
    },
  },
  CopyTo: {
    type: 'CopyTo',
    cnName: '抄送',
    dataType: '',
    identifier: `i_${uuid().replace(/-/g, '')}_i`,
    description: '',
    dataKey: '',
    CopyTo: {},
  },
}

const initEllipseConfig = () => {
  Shape.Ellipse.config({
    inherit: 'ellipse',
    label: '开始',
    shape: 'ellipse',
    x: document.body.offsetWidth / 2 - 350,
    y: document.body.offsetHeight / 2 - 100,
    width: 26,
    height: 26,
    attrs: {
      body: {
        stroke: 'rgba(102, 204, 58, 0.46)',
        fill: 'rgba(102, 204, 58, 0.36)',
        cx: 13,
        cy: 13,
        rx: 13,
        ry: 13,
      },
      title: {
        text: '开始',
        refX: -1,
        refY: -8,
        fontSize: 14,
        textAnchor: 'middle',
        textVerticalAnchor: 'bottom',
        fill: 'rgba(5,6,26,0.66)',
        'text-anchor': 'start',
      },
    },
    markup: [
      {
        tagName: 'ellipse',
        selector: 'body',
      },
      {
        tagName: 'text',
        selector: 'title',
      },
    ],
    ports: {
      groups: {
        out: {
          position: 'bottom',
          attrs: {
            circle: {
              r: 5,
              magnet: true,
              stroke: 'rgba(5,6,26,0.66)',
              strokeWidth: 1,
              fill: '#fff',
              refY: 0,
              refX: 0,
            },
          },
          label: {
            position: 'bottom', // 标签位置
          },
        },
      },
      items: [{ group: 'out' }],
    },
  })
}

// 转化JSON
const generateDataJson = (X6Json) => {
  // 2.获取所有的节点
  const nodes = X6Json.cells.filter((item) => item.shape !== 'edge')
  // 3.获取所有的连线
  const edges = X6Json.cells.filter((item) => item.shape === 'edge')
  const States = {}
  let StartAt = ''
  // 4.后端需要的节点数据
  if (nodes && nodes.length > 0) {
    nodes.forEach(({ id, data }) => {
      // 取出开始节点的id
      if (data.type) {
        if (['StartEvent'].includes(data.type)) {
          StartAt = id
        }
      }
      if (data.shape !== 'edge') States[id] = data
      // 获取当前节点为开始的所有边
      const sourceEdges = edges.filter(
        (item) => item.source && item.source.cell === id
      )
      // 其他节点设置下一步id
      if (data) {
        if (!['end'].includes(data.type)) {
          if (
            sourceEdges &&
            sourceEdges.length > 0 &&
            sourceEdges[0].target &&
            sourceEdges[0].target.cell
          ) {
            const list = []
            for (let index = 0; index < sourceEdges.length; index++) {
              const item = sourceEdges[index]
              if (item.target) {
                list.push(item.target.cell)
              }
            }
            States[id].Next = list
          }
        }
      }
    })
  }

  return { generateData: { StartAt, States } }
}

const approvalBaseUrl = 'https://open.3as.cn/flow'

const approvalBaseUrlForm = 'https://open.3as.cn/form'

// 更改JSON
const updateJson = async (id, params) => {
  await put(`${approvalBaseUrl}/flowApi/workflowDefinition/${id}`, params)
}


export {
  approvalConfig,
  getOrg,
  getApp,
  getUser,
  leftNode,
  nodeInfoList,
  initEllipseConfig,
  generateDataJson,
  updateJson,
  approvalBaseUrl,
  approvalBaseUrlForm,
}

